import "../style/list.css";
import { EUV } from "@hongweifei/euv";
import { StatusCode } from "../api/web-result.js";
import { getUserInfo, logout as userLogout } from "../api/user";
import { getWJListByUsername, deleteWJ as requestDeleteWJ } from "../api/wj";



new EUV({
    elementSelector: "#app",
    async mounted() {
        setInterval(() => {
            const date = new Date();
            this.data.nowTime = date.toLocaleDateString() + "    " + date.toLocaleTimeString();
        }, 500);

        const userInfoResult = await getUserInfo();
        if (userInfoResult.code !== StatusCode.SUCCESS) {
            alert(userInfoResult.message);
            window.location.href = "../index.html";
            return;
        }
        const user = userInfoResult.data;
        if (!user) {
            alert("错误");
            window.location.href = "../index.html";
            return;
        }
        this.data.user = user;
        this.data.login = true;


        const wjList = (await getWJListByUsername(user.username)).data;
        const liTemplate = document.querySelector("#template-wj-item").content.children[0];
        const ul = document.querySelector(".container-right-list");
        wjList.forEach((item) => {
            const li = liTemplate.cloneNode(true);
            li.querySelector("h3").textContent = item.title;
            li.querySelector("time").textContent = item.date;
            li.querySelector(".button-delete").onclick = () => {
                if (!window.confirm("是否删除")) {
                    requestDeleteWJ(item)
                    .then(result => {
                        alert(result.message);
                        if (result.code === StatusCode.SUCCESS) {
                            li.remove();
                        }
                    });
                }
            };
            li.querySelector(".button-edit").onclick = () => {
                window.location.href = `./edit.html?action=update&title=${item.title}`;
            }
            li.querySelector(".button-view").onclick = () => {
                window.open(`./wj.html?creator=${item.creator}&title=${item.title}`);
            };
            ul.appendChild(li);
        });

        const accordionButton = document.getElementById("button-accordion");
        accordionButton.onclick = () => {
            accordionButton.classList.toggle("active");
        };
    },

    data: {
        nowTime: (function() {
            const date = new Date();
            return date.toLocaleDateString() + "    " + date.toLocaleTimeString();
        })(),
        user: {},
        login: false,
    },

    methods: {
        logout() {
            userLogout();
            this.data.user = {};
            this.data.login = false;
            window.location.reload();
        },
    }
});


